package com.wpp.algorithm.lagou.question;

import java.util.Objects;

/**
 * @author wangpengpeng
 * @version 1.0
 * @description:
 * @date 2025/3/11 19:07
 */
public class A002两数相加 {

    static class ListNode {
        public int val;
        public ListNode next;

        public ListNode() {}
        public ListNode(int val) {
            this.val = val;
        }
        public ListNode(int val, ListNode next) {
            this.val = val; this.next = next;
        }


    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        int v1 = 0;
        int v2 = 0;
        int sum = 0;
        // 进位
        int temp = 0;

        ListNode headNode = new ListNode();
        ListNode curNode = headNode;

        while (Objects.nonNull(l1) || Objects.nonNull(l2) || temp != 0 ) {

            if (Objects.isNull(l1)){
                v1 = 0;
            } else {
                v1 = l1.val;
                l1 = l1.next;
            }

            if (Objects.isNull(l2)){
                v2 = 0;
            } else {
                v2 = l2.val;
                l2 = l2.next;
            }

            sum = v1 + v2 + temp;
            // 13%10=3
            // 13/10=1
            temp = sum / 10;

            curNode.next = new ListNode(sum % 10);
            curNode = curNode.next;
        }

        return headNode.next;
    }

    public static void main(String[] args) {

        ListNode ln = new ListNode(2,new ListNode(4,new ListNode(3)));
        ListNode ln1 = new ListNode(5,new ListNode(6,new ListNode(4)));

        ListNode listNode = addTwoNumbers(ln, ln1);
        while (Objects.nonNull(listNode)){

            System.out.print(listNode.val);
            listNode = listNode.next;
        }


    }
}
